<!--
 * @Description: 商品列表》添加商品
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-01 20:40:32
 * @LastEditTime: 2021-10-02 15:31:42
-->
<template>
  <div class="list-add-container">
    <!--  头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wlecome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容card -->
    <el-card>
      <el-alert title="新建商品信息"
        type="info"
        center
        show-icon
        closable>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200"
        :active="activeTab"
        finish-status="finish"
        align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 新商品信息 -->
      <el-form ref="goodFormRef"
        :model="goodForm"
        label-width="auto"
        :rules="goodFormRules"
        status-icon
        label-position="top">
        <!-- 具体的tab  -->
        <el-tabs tab-position="left"
          :before-leave="checkCate"
          @tab-click="tabClick"
          v-model="tabsValue">
          <el-tab-pane label="基本信息">
            <el-form-item prop="goods_name"
              label="商品名称"
              name="0">
              <el-input v-model="goodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格"
              prop="goods_name">
              <el-input v-model="goodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight"
              label="商品重量">
              <el-input v-model="goodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number"
              label="商品数量">
              <el-input v-model="goodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_cat"
              label="商品分类">
              <el-cascader v-model="goodForm.goods_cat"
                :options="categories"
                :props="cascaderProps"
                @change="handelChange"
                clearable></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数"
            name="1">
            <el-row v-for="attr in manyTabData"
              :key="'many'+attr.attr_id">
              <el-col>{{attr.attr_name}}</el-col>
              <el-col>
                <el-checkbox-group v-model="attr.attr_vals">
                  <el-checkbox v-for="(val,index) in attr.attr_vals"
                    :key="val+'_'+index"
                    :label="val"
                    border
                    size="mini">{{val}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品属性"
            name="2">

            <el-row v-for="attr in onlyTabData"
              :key="'only'+attr.attr_id">
              <el-col>{{attr.attr_name}}</el-col>
              <el-col class="attr_col_input">
                <el-input placeholder="请输入内容"
                  v-model="attr.attr_vals"
                  clearable>
                </el-input>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品图片"
            name="3">

            <el-upload :action="uploadUrl"
              list-type="picture-card"
              :headers="headerObj"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%"
                :src="dialogImageUrl"
                alt="">
            </el-dialog>

          </el-tab-pane>
          <el-tab-pane label="商品内容"
            name="4">
            <quill-editor v-model="goodForm.goods_introduce" />
            <el-row>
              <el-col>
                <el-button type="primary"
                  @click="addNewGood">提交新商品</el-button>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'Add',
  created() {
    this.getAllCategories()
  },
  data() {
    return {
      tabsValue: '0',
      // 商品信息表岛
      goodForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      goodFormRules: {
        goods_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入...', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入...', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入...', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'change' }]
      },
      // 所处的步骤
      activeTab: 0,
      // 类别
      categories: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover'
      },
      cascader_value: [],
      // 商品参数
      cateId: 0,
      // attributes: [],
      checkedVals: [],
      // 动态参数
      manyTabData: [],
      // 静态属性
      onlyTabData: [],
      // 图片上传
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      }
    }
  },
  methods: {
    // 图片上传
    handleSuccess(response, file, fileList) {
      console.log(fileList)
      if (response.meta.status !== 200) {
        // todo 调用图片remove
        return this.$message.error(response.meta.msg)
      }
      this.$message.success(response.meta.msg)
      const pics = []
      fileList.forEach(item => {
        const p = {
          pic: item.response.data.tmp_path
        }

        pics.push(p)
      })
      this.goodForm.pics = pics
      // console.log(this.goodForm.pics)
    },
    handleRemove(file) {
      console.log(file)
      const tmpPath = file.response.data.tmp_path
      const index = this.goodForm.pics.findIndex(item => item.tmp_path === tmpPath)
      this.goodForm.pics.splice(index, 1)
      console.log(this.goodForm.pics)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    tabClick(tab) {
      // console.log(tab.name)
      this.activeTab = parseInt(this.tabsValue)
      if (tab.name === '1') {
        // 进入商品参数tab，获取动态参数
        this.getManyAttributes()
      } else if (tab.name === '2') {
        // 进入商品属性tab，获取静态属性
        this.getOnlyAttributes()
      }
    },
    // 获取参数列表
    async getManyAttributes() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'many'
        }
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // 对于动态参数，把字符串型的属性值转换成数组
      res.data.forEach(item => {
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(',')
        }
      })

      this.manyTabData = res.data
      // this.$message.success(res.meta.msg)
      console.log(this.manyTabData)
    },
    async getOnlyAttributes() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'only'
        }
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.onlyTabData = res.data
      // this.$message.success(res.meta.msg)
      console.log(this.onlyTabData)
    },
    // 获取类别信息
    async getAllCategories() {
      const { data: res } = await this.$http.get('categories')

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // this.$message.success(res.meta.msg)
      this.categories = res.data
    },
    // 商品分类切换
    handelChange() {
      const len = this.goodForm.goods_cat.length
      if (len !== 3) {
        this.goodForm.goods_cat = []
        return false
      }
      this.cateId = this.goodForm.goods_cat[len - 1]
    },
    // 切换tab前的检查
    checkCate(activeName, oldActiveName) {
      // console.log(activeName, oldActiveName)
      if (activeName !== '0') {
        if (this.goodForm.goods_cat.length !== 3) {
          this.$message({
            message: '请先选择3级商品类别！',
            type: 'warning'
          })
          return false
        }
        return true
      }
    },

    // 添加商品
    addNewGood() {
      this.$refs.goodFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('表单数据不合法！')
          return false
        }
        const form = _.cloneDeep(this.goodForm)
        // 类别由数组转成,分割字符串
        form.goods_cat = this.goodForm.goods_cat.join(',')
        // 将动态和静态属性变为统一的对象数组
        const attrs = []
        this.manyTabData.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }

          attrs.push(attr)
        })
        this.onlyTabData.forEach(item => {
          const attr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }

          attrs.push(attr)
        })

        form.attrs = attrs
        console.log(form)

        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)
        this.$router.replace('/goods')
      })
    }
  }
}
</script>

<style>
.el-steps {
  margin: 20px 0;
}
.el-checkbox-group {
  margin: 8px 0;
}

.attr_col_input {
  margin: 5px 0 15px 0;
}

.ql-container {
  height: 300px !important;
}

.el-row {
  margin: 15px 0 0 10px;
}
</style>
